<template>
  <div class="container">
    <div class="blogging width">
      <el-form ref="form" label-width="80px" class="form">
        <el-form-item label="文章标题">
          <el-input v-model.trim="title"></el-input>
        </el-form-item>
        <el-form-item label="文章地址">
          <el-input v-model="address" style="width: 400px"></el-input>
          <el-button class="btn" type="primary" @click="getArticle">获取文章</el-button>
          <span class="fz12">(支持csdn 掘金 简书 知乎)</span>
        </el-form-item>
        <el-form-item label="文章内容:">
          <!-- 引入富文本编辑器 -->
          <MyMarkdownEditor v-model="content" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" round @click="downloadMarkdown">下载morkdown</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getArticleByUrl } from '@/api/article'
import { isUrlValid } from '@/utils/validate'
export default {
  data() {
    return {
      title: '',
      address: '',
      content: ''
    }
  },
  methods: {
    // 爬虫获取文章
    async getArticle() {
      try {
        if (!this.address || !isUrlValid(this.address)) {
          this.$message({
            type: 'error',
            message: '请输入文章地址,目前只支持juejin,csdn,weixin公众号文章',
            offset: 80
          })
          return false
        }
        const params = this.address
        const {
          data: { content, title }
        } = await getArticleByUrl({ url: params })
        this.content = content
        this.title = title
      } catch (error) {
        console.log(error)
        this.$message({
          type: 'error',
          message: '获取文章失败,请检查地址是否正确',
          offset: 80
        })
      }
    },
    // 下载 Markdown 文件
    downloadMarkdown() {
      const filename = this.title ? this.title + '.md' : 'download.md'
      console.log('filename: ', filename)
      const blob = new Blob([this.content], { type: 'text/plain' })
      // 创建一个临时url用于下载
      const url = window.URL.createObjectURL(blob)
      // 创建一个锚点元素用于下载
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      // 触发锚点的点击事件
      link.click()
      // 使用 revokeObjectURL 方法释放之前创建的 Blob URL，帮助管理内存，防止内存泄漏。
      window.URL.revokeObjectURL(url)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f2f3f5;
}
.blogging {
  padding-top: 80px;
  .form {
    width: 800px;
    padding-bottom: 5px;
  }
  .btn {
    margin-left: 20px;
    margin-right: 5px;
  }
}
</style>
